//
//  ViewController.m
//  AVAssetExportSession
//
//  Created by Xwoder on 17/2/4.
//  Copyright © 2017年 Xwoder. All rights reserved.
//

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>

#define DocumentDirectory NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject

@interface ViewController ()

@property (nonatomic, strong) AVAssetExportSession *session;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"movie" withExtension:@"mp4"];
    
    AVAsset *asset = [AVAsset assetWithURL:url];
    
    AVAssetExportSession *session = [AVAssetExportSession exportSessionWithAsset:asset presetName:AVAssetExportPresetHighestQuality];
    session.timeRange = CMTimeRangeMake(kCMTimeZero, CMTimeMake(5, 1));
    session.outputFileType = AVFileTypeMPEG4;
    session.shouldOptimizeForNetworkUse = YES;

    NSString *outputFilePath = [DocumentDirectory stringByAppendingPathComponent:@"output.mp4"];
    session.outputURL = [NSURL fileURLWithPath:outputFilePath];
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:outputFilePath]) {
        [[NSFileManager defaultManager] removeItemAtPath:outputFilePath error:NULL];
    }
    
    [session exportAsynchronouslyWithCompletionHandler:^{
        NSLog(@"%@", session.outputURL);
        if (session.status == AVAssetExportSessionStatusFailed) {
            NSLog(@"AVAssetExportSessionStatusFailed");
        } else if(session.status == AVAssetExportSessionStatusCompleted) {
            NSLog(@"AVAssetExportSessionStatusCompleted");
        }
    }];
    
    self.session = session;
}

@end
